import request from '@/util/request';
import type { ApiResponse } from '@/types/note/note';
import { UserData } from '@/types/UserData';
import { CourseShow } from './course/Course';

const STORAGE_KEY = 'UserInfo';
const TOKEN_EXPIRE_TIME = 30 * 60 * 1000; // 30分钟

// 图片验证码
export interface ImageCode {
    code: string;
    sessionId: string;
}

// 短信验证码
export interface SmsCode {
    phoneNumber: string;
    code?: string;
    imageCode: ImageCode;
}

// 登录上传数据
export interface LoginData {
    phoneNumber: string;
    password: string;
    code: ImageCode;
}

//注册上传数据
export interface RegisterData {
    username: string;
    avatar: string;
    phoneCode: number;
    phoneNumber: number;
    password: string;
}

export const codeApi = {
	// 获取图片验证码
	getImageCode : async (): Promise<ApiResponse<ImageCode>> => {
		try {
			const response = await request.post<ApiResponse<ImageCode>>('code/image');
			return response.data;
		} catch (error) {
			throw error;
		}
	},
    // 获取短信验证码
    getSmsCode : async (SmsCode: SmsCode): Promise<ApiResponse<boolean>> => {
        try {
            const response = await request.post<ApiResponse<boolean>>('code/sms', SmsCode);
            return response.data;
        } catch (error) {
            throw error;
        }
    },

}

export const userApi = {
    login: async (formData: LoginData): Promise<ApiResponse<boolean>> => {
        try {
            const response = await request.post<ApiResponse<string>>('login/phoneLogin', formData);
            console.log(response.data);
            // 判断是否登录成功
            var success = response.data.code === 200 && response.data.data !== null;
            if (success) {
                // 保存Token到本地存储
                console.log(response.data.data);
                request.setToken(response.data.data);
            }
            return {
                code: response.data.code,
                message: response.data.message,
                data: success
            };
        } catch (error) {
            throw error;
        }
    },
    // 注册
    register: async (RegisterData): Promise<ApiResponse<boolean>> => {
        try {
            const response = await request.post<ApiResponse<boolean>>('register/phoneRegister', RegisterData);
                return response.data;
            } catch (error) {
                throw error;
        }
    },
    // 判断token是否过期
    isTokenExpired: async (): Promise<boolean> => {
        try {
            const response = await request.post<ApiResponse<boolean>>('login/isTokenExpired');
            return response.data.data;
        } catch (error) {
            throw error;
        }
    },
    // 获取登录用户信息
    getLoginUserData: async (update?: Boolean): Promise<UserData> => {
        if (update) { // 如果update为true，则清除本地存储 (强制更新)
            localStorage.removeItem(STORAGE_KEY);
        }

        // 判断token是否过期
        if (await userApi.isTokenExpired()) {
            userApi.logout(); // token 过期，清除本地存储并退出登录
            return null;
        }

        // 从本地存储恢复数据
        const savedData = localStorage.getItem(STORAGE_KEY);
    
        if (savedData) {
            const parsedData = JSON.parse(savedData);
            const now = new Date().getTime();
            const savedTime = new Date(parsedData.savedTime).getTime();
            
            // 检查是否过期
            if (now - savedTime < TOKEN_EXPIRE_TIME) {
                console.log("从本地存储恢复数据");
                return parsedData;
            }
        }

        console.log("从服务器获取数据");
        try {
            const response = await request.post<ApiResponse<UserData>>('users/getLoginUser');
            if (response.data.code !== 200) {
                return null;
            }
            
            response.data.data.savedTime = new Date().toISOString();
			localStorage.setItem(STORAGE_KEY, JSON.stringify(response.data.data));
            return response.data.data;
        } catch (error) {
            return null;
        }
    },
    course: {
        // 获取创建的课程
        getCreateCourse: async (): Promise<CourseShow[]> => {
            try {
                const response = await request.post<ApiResponse<CourseShow[]>>('users/getCreateCourse');
                return response.data.data;
            } catch (error) {
                throw error;
            }
        },
        // 获取加入的课程
        getJoinCourse: async (): Promise<CourseShow[]> => {
            try {
                const response = await request.post<ApiResponse<CourseShow[]>>('users/getJoinCourse');
                return response.data.data;
            } catch (error) {
                throw error;
            }
        },
        // 获取收藏的课程
        getCollectCourse: async (): Promise<CourseShow[]> => {
            try {
                const response = await request.post<ApiResponse<CourseShow[]>>('users/getCollectCourse');
                return response.data.data;
            } catch (error) {
                throw error;
            }
        }
    },
    // 退出登录
    logout: () => {
        localStorage.removeItem(STORAGE_KEY);
        request.clearToken();
    },
}